import router from './router'
import { useAppStoreWithOut } from '@/store/modules/app'
import type { RouteRecordRaw } from 'vue-router'
import { useTitle } from '@/hooks/web/useTitle'
import { useNProgress } from '@/hooks/web/useNProgress'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { NO_REDIRECT_WHITE_LIST } from '@/constants'
import { useUserStoreWithOut } from '@/store/modules/user'
import { getUserInfo } from './api/login'

const { start, done } = useNProgress()

const { loadStart, loadDone } = usePageLoading()

const permissionStore = usePermissionStoreWithOut()

/**
 * 加载路由
 */
const loadRoute = async () => {
  const appStore = useAppStoreWithOut()
  const userStore = useUserStoreWithOut()
  // 开发者可根据实际情况进行修改
  const roleRouters = userStore.getRoleRouters || []

  // 是否使用动态路由
  if (appStore.getDynamicRouter) {
    appStore.serverDynamicRouter
      ? await permissionStore.generateRoutes('server', roleRouters as AppCustomRouteRecordRaw[])
      : await permissionStore.generateRoutes(
          'frontEnd',
          undefined,
          userStore.getUserInfo?.extraProperties.permissions
        )
  } else {
    await permissionStore.generateRoutes('static')
  }

  permissionStore.getAddRouters.forEach((route) => {
    router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
  })

  permissionStore.setIsAddRouters(true)
}

/**
 * 加载用户信息
 */
const loadUserInfo = async () => {
  const userStore = useUserStoreWithOut()
  const res = await getUserInfo()
  userStore.setUserInfo(res)
}

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStoreWithOut()
  start()
  loadStart()
  if (userStore.getToken) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      try {
        if (!userStore.getUserInfoLoaded) {
          await loadUserInfo()
        }

        const prevIsAddRouters = permissionStore.getIsAddRouters
        if (!permissionStore.getIsAddRouters) {
          await loadRoute()
        }
        !prevIsAddRouters ? next({ ...to, replace: true }) : next()
      } catch (error) {
        next('/500')
        return
      }
    }
  } else {
    if (NO_REDIRECT_WHITE_LIST.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
    }
  }
})

router.afterEach((to) => {
  useTitle(to?.meta?.title as string)
  done() // 结束Progress
  loadDone()
})
